package com.huai.demo_test1.controller;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;

/**
 * @author lenovo
 */
@RestController
@Slf4j
@RequestMapping("/esTest")
public class ElasticSearchTestController {

    /**
     * 通过http请求的端口号是9200，通过客户端请求的端口号是9300
    */
    private static int port = 9300;
    private static String host = "192.168.3.182";

    @RequestMapping("/connect")
    public String connect() throws UnknownHostException {
        //1、指定es集群  cluster.name 是固定的key值，docker-cluster是ES集群的名称
        Settings settings = Settings.builder()
                                    //设置es集群名称
                                    .put("cluster.name", "elasticsearch")
                                    //增加嗅探机制，找到es集群
                                    .put("client.transport.sniff", true)
                                    .build();
        /*
         * 创建客户端，所有的操作都由客户端开始，这个就好像是JDBC的Connection对象
         * 用完记得要关闭
         */
        //2.创建访问ES服务器的客户端
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddresses(
                new TransportAddress(InetAddress.getByName(host), port));
        return client.toString();
    }

    @RequestMapping("/testInsert")
    public String testInsert() throws IOException {
        //1、指定es集群  cluster.name 是固定的key值，docker-cluster是ES集群的名称
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //获取es主机中节点的ip地址及端口号(以下是单个节点案例)
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddresses(
                new TransportAddress(InetAddress.getByName(host), port));
        //将数据转换成文档的格式（后期可以使用java对象，将数据转换成json对象就可以了）
        XContentBuilder doContentBuilder = XContentFactory.jsonBuilder()
                                                          .startObject()
                                                          .field("id", "1")
                                                          .field("name", "huai")
                                                          .field("address", "上海虹桥")
                                                          .field("age", "20")
                                                          .field("date", "2018-05-20")
                                                          .field("url", "www.huai.com")
                                                          .endObject();
        //添加文档  index1:索引名 blog:类型 10:id
        //.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) 代表插入成功后立即刷新，因为ES中插入数据默认分片要1秒钟后再刷新

        IndexResponse response = client.prepareIndex("estest", "student", "1")
                                       .setSource(doContentBuilder).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get();
        //打印出CREATED 表示添加成功
        log.info(String.valueOf(response.status()));
        return response.status().toString();
    }

    @RequestMapping("testGet/{id}")
    public String testGet(@PathVariable("id") String id) throws UnknownHostException {
        //1、指定es集群  cluster.name 是固定的key值，docker-cluster是ES集群的名称
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //获取es主机中节点的ip地址及端口号(以下是单个节点案例)
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddresses(
                new TransportAddress(InetAddress.getByName(host), port));
        //实现数据查询(指定_id查询) 参数分别是 索引名，类型名  id
        GetResponse getResponse = client.prepareGet("estest", "student", id).get();
        String sourceAsString = getResponse.getSourceAsString();
        log.info(sourceAsString);
        client.close();//关闭客户端
        return sourceAsString;
    }

    @RequestMapping("testUpdate/{id}")
    public String testUpdate(@PathVariable("id") String id) throws IOException, InterruptedException, ExecutionException {
        //1、指定es集群  cluster.name 是固定的key值，docker-cluster是ES集群的名称
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //获取es主机中节点的ip地址及端口号(以下是单个节点案例)
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddresses(
                new TransportAddress(InetAddress.getByName(host), port));
        UpdateRequest request = new UpdateRequest();
        request.index("estest")
               .type("student")
               .id(id)
               .doc(
                       XContentFactory.jsonBuilder()
                                      .startObject()
                                      .field("age", "33")
                                      .endObject()
               );
        UpdateResponse response = client.update(request).get();
        //控制台出现OK 代表更新成功
        log.info(String.valueOf(response.status()));
        return response.status().toString();
    }

}
